package loteriamais.util;

import java.util.Properties;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailUtil {
	
	public static boolean sendingMail(String address, String subject, String text) {
		final ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
		Properties props = new Properties();
		boolean enviou = false;
		
		props.put("mail.transport.protocol", extContext.getInitParameter("mail.transport.protocol"));
		props.put("mail.smtp.host", extContext.getInitParameter("mail.smtp.host"));
		props.put("mail.smtp.socketFactory.port", extContext.getInitParameter("mail.smtp.socketFactory.port"));
		props.put("mail.smtp.socketFactory.fallback", extContext.getInitParameter("mail.smtp.socketFactory.fallback"));
		props.put("mail.smtp.starttls.enable", extContext.getInitParameter("mail.smtp.starttls.enable"));
		props.put("mail.smtp.auth", extContext.getInitParameter("mail.smtp.auth"));
		props.put("mail.smtp.port", extContext.getInitParameter("mail.smtp.port"));
		
		try {
			Session session = Session.getDefaultInstance(props, new Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(extContext.getInitParameter("emailAutenticacao"), extContext.getInitParameter("senhaAutenticacao"));
				}
			});
			session.setDebug(true);
			
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("marcia.rodrigo.maria@hotmail.com"));
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address));
			message.setSubject(subject);
			message.setText(text);
			Transport.send(message);
			enviou = true;
		} catch(MessagingException e) {
			System.out.println(e.getMessage());
		}
		return enviou;
	}
}
